package rohan.apps.mileagetracker;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.GeolocationPermissions;
import android.webkit.GeolocationPermissions.Callback;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class CarMileageTrackerActivity extends Activity implements GeolocationPermissions.Callback {
	WebView wvMain;
	final String APP_URL ="http://car-mileage.rohanghatpande.com/apps/car-mileage/";
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        wvMain=(WebView)findViewById(R.id.wvMain);
        
        
        
       //set settings
        wvMain.getSettings().setJavaScriptEnabled(true);
        wvMain.getSettings().setDomStorageEnabled(true);
        wvMain.getSettings().setGeolocationEnabled(true);
        wvMain.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        wvMain.getSettings().setSavePassword(true);
        wvMain.getSettings().setAppCacheEnabled(true);  
        wvMain.getSettings().setDatabaseEnabled(true);
        wvMain.setVerticalScrollBarEnabled(false);
        
        //set WebView client to prevent redirects outside of application
        wvMain.setWebViewClient(new  CustomWebViewClient(wvMain.getContext()));
        
        //setup geolocation to allow location tracking        
        _WebChromeClient _wcc = new _WebChromeClient();
        wvMain.setWebChromeClient(_wcc);
        String origin = ""; 
        _wcc.onGeolocationPermissionsShowPrompt(origin, this);
        
        //load URL
        wvMain.loadUrl(APP_URL);
        
    }
    public boolean onKeyDown(int keyCode, KeyEvent event) {  
 	   if ((keyCode == KeyEvent.KEYCODE_BACK) && wvMain.canGoBack()) {  
 		   wvMain.goBack();  
 	     return true;  
 	   }  
 	   return super.onKeyDown(keyCode, event);  
 	 }
    
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		//menu.getItem(0).setIcon(android.R.drawable.ic _menu_revert);
    	MenuInflater inflater = getMenuInflater();		
		inflater.inflate(R.menu.mainmenu, menu);		
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch(item.getItemId()){
			case R.id.mnuRefresh:
				Toast.makeText(this, "Reloading..", Toast.LENGTH_SHORT).show();
				wvMain.reload();
				break;
			case R.id.mnuReset:
				Toast.makeText(this, "Reseting...", Toast.LENGTH_SHORT).show();
				wvMain.setWebViewClient(new CustomWebViewClient(wvMain.getContext()));
				wvMain.clearCache(true);
		        wvMain.loadUrl(APP_URL);		        
		        break;				
		}		
		return true;
	}
	@Override
	public void invoke(String origin, boolean allow, boolean remember) {
		// TODO Auto-generated method stub		
	}
	
	final class _WebChromeClient extends WebChromeClient {

		boolean confirmRetVal;
		@Override
		public void onGeolocationPermissionsShowPrompt(String origin,Callback callback) {
			// TODO Auto-generate	d method stub
			super.onGeolocationPermissionsShowPrompt(origin, callback);
			callback.invoke(origin, true, false);
			}
		@Override
		public void onProgressChanged(WebView view, int progress) {
		    // Activities and WebViews measure progress with different scales.
		    // The progress meter will automatically disappear when we reach 100%
			CarMileageTrackerActivity.this.setProgress(progress * 100);
		}

		@Override
		public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
		   // Log.d(LOG_TAG, message);
		    // This shows the dialog box.  This can be commented out for dev
		    AlertDialog.Builder alertBldr = new AlertDialog.Builder(CarMileageTrackerActivity.this);
		    alertBldr.setMessage(message);
		    alertBldr.setTitle("Alert");
		    alertBldr.show();
		    result.confirm();
		    return true;
		  }
		
		 @Override
		    public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
		        new AlertDialog.Builder(CarMileageTrackerActivity.this)
		        .setTitle("App Titler")
		        .setMessage(message)
		        .setPositiveButton(android.R.string.ok,
		                new DialogInterface.OnClickListener()
		        {
		            public void onClick(DialogInterface dialog, int which)
		            {
		                result.confirm();
		            }
		        })
		        .setNegativeButton(android.R.string.cancel,
		                new DialogInterface.OnClickListener()
		        {
		            public void onClick(DialogInterface dialog, int which)
		            {
		                result.cancel();
		            }
		        })
		        .create()
		        .show();

		        return true;
		    }
	}
	
	final class CustomWebViewClient extends WebViewClient {
	    Context context;
	    ProgressDialog pd = null;


	    public CustomWebViewClient (Context c){
	        context = c;
	        
	    }

	    public void onPageFinished(WebView view, String url){	  
	    	super.onPageFinished(view, url);
	    	if(pd!=null){	    		
	    		//pd.dismiss();
	    		pd.dismiss();
	    	}	    		    	
	    	//Toast.makeText(CarMileageTrackerActivity.this, "onPageFinished..." +url, T oast.LENGTH_SHORT).show();
	    }
	    
	    @Override
	    public void onPageStarted(WebView view, String url, Bitmap favicon) {   	
		    
	    	super.onPageStarted(view, url, favicon);
	    	// TODO Auto-generated method stub
	    	pd = ProgressDialog.show(context, "", "Loading. Please wait...", true);	        
		    //pd.setCancelable(true);
		    pd.setCanceledOnTouchOutside(true);
	    }
	   /* 
	   Handler handler = new Handler(){
		   @Override
		   public void handleMessage(Message msg) {
		       if(pd!=null || pd.isShowing())
		    	   pd.dismiss();	
		       pd=null;
	        }
		   
	   };
	   */
	   
	   public boolean shouldOverrideUrlLoading(final WebView view, final String url) {	 
	        view.loadUrl(url);  
	        return true;
	    } 
	   
	   @Override
	   public void onLoadResource(WebView view, String url) {
			// TODO Auto-generated method stub 
			//this guy loads all the web resources
			//Toast.makeText(CarMileageTrackerActivity.this, " onLoadResource..." +url, Toast.LENGTH_SHORT).show();
			super.onLoadResource(view, url);
		}
	   

	}
}
